package com.enjoyor.soa.traffic.frame.interceptor;

import com.enjoyor.filter.SSOClientfilter;
import com.enjoyor.soa.traffic.frame.annotation.Auth;
import com.enjoyor.soa.traffic.frame.security.bean.dto.UserDto;
import com.enjoyor.soa.traffic.util.helper.JsonHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "sso.client")
public class SSOInterceptor implements HandlerInterceptor {

    public Map<String, String> filter = new HashMap<String, String>();

    private Method method = null;

    private Class<?> clazz = null;

    private HandlerMethod handlerMethod = null;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if (!handler.getClass().isAssignableFrom(HandlerMethod.class))
            return true;

        if (!getFilter().get("startUp").equals("1"))
            return true;

        String token = request.getHeader("token") == null ? request.getParameter("token") : request.getHeader("token");

        handlerMethod = (HandlerMethod) handler;
        method = handlerMethod.getMethod();
        clazz = method.getDeclaringClass();

        if (clazz.isAnnotationPresent(Auth.class) || method.isAnnotationPresent(Auth.class)) {

            String[] excludes = clazz.getAnnotation(Auth.class).excludes();

            if (excludes != null && excludes.length > 0)
                if (Arrays.asList(excludes).contains(method.getName()))
                    return true;

            if (!StringUtils.isBlank(token)) {

                try {
                	 String authorizeStr = JsonHelper.beanToJsonStr(SSOClientfilter.getUserInfo(token));
                    if (authorizeStr != null && !StringUtils.isBlank(authorizeStr)) {
                        UserDto currentUser = (UserDto) JsonHelper.jsonToObject(authorizeStr, UserDto.class);
                        request.setAttribute("currentUser", currentUser);
                        request.setAttribute("systemKey", getFilter().get("systemKey"));
                        request.setAttribute("token", token);
                        return true;
                    } else
                        response.sendError(HttpServletResponse.SC_FORBIDDEN, "token验证失败，请检查token！");

                } catch (Exception e) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "token验证失败，请检查token！");
                }

            } else
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "token不能为空！");
        } else{
            response.setHeader("Access-Control-Allow-Origin", "*");
            return true;
        }
        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
            ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object,
            Exception exception) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
    }

    public Map<String, String> getFilter() {
        return filter;
    }

    public void setFilter(Map<String, String> filter) {
        this.filter = filter;
    }

}
